<?php

namespace app\common\library;

use think\Config;
use addons\epay\library\Service as PayService;
use Yansongda\Pay\Pay;
class Refund
{
    /**
     * 支付宝退款
     * @param string $orderNo 订单号
     * @param float $amount 退款金额
     * @param string $reason 退款原因
     * @return array
     * @throws \Exception
     */
    public static function alipay($orderNo, $amount, $reason = '正常退款',$out_request_no)
    {
        $config = PayService::getConfig('alipay');
        
        // 使用epay插件的支付功能
        $pay =  Pay::alipay($config);
        
        $params = [
            'out_trade_no' => $orderNo,
            'refund_amount' => number_format($amount, 2, '.', ''),
            'refund_reason' => $reason,
            'out_request_no' => $out_request_no
        ];
        
        try {
            $result = $pay->refund($params);
            
            if (isset($result['code']) && $result['code'] === '10000') {
                return [
                    'status' => true,
                    'refund_no' => $result['trade_no'],
                    'message' => '退款成功'
                ];
            }
            throw new \Exception($result['sub_msg'] ?? '支付宝退款失败');
        } catch (\think\exception\PDOException $e) {
            throw new \Exception($e->getMessage());
        }
    }
    
    /**
     * 微信退款
     * @param string $orderNo 订单号
     * @param float $totalAmount 订单总金额
     * @param float $refundAmount 退款金额
     * @param string $reason 退款原因
     * @return array
     * @throws \Exception
     */
    public static function wechat($orderNo, $totalAmount, $refundAmount, $reason = '正常退款',$out_request_no)
    {
        $config = PayService::getConfig('wechat');
        // 使用epay插件的支付功能
        $pay =  Pay::wechat($config);
        
        $params = [
            'out_trade_no' => $orderNo,
            'total_fee' => $totalAmount * 100, // 微信金额单位是分
            'refund_fee' => $refundAmount * 100,
            'refund_desc' => $reason,
            'out_refund_no' => $out_request_no
        ];
        
        try {
            $result = $pay->refund($params);
            
            if ($result['return_code'] === 'SUCCESS' && $result['result_code'] === 'SUCCESS') {
                return [
                    'status' => true,
                    'refund_no' => $result['refund_id'],
                    'message' => '退款成功'
                ];
            }
            throw new \Exception($result['err_code_des'] ?? '微信退款失败');
        } catch (\think\exception\PDOException $e) {
            throw new \Exception($e->getMessage());
        }
    }
}